from owl_ai.domain.chat_entity import ChatMessage, ChatFileMessage
from owl_ai.service import ChatFilesService


class ChatFlowGraphAppService:
    """
    聊天流图应用服务
    """

    @classmethod
    def convert_message_to_llm(cls, chat_message: ChatMessage):
        """
        将消息转换为LLM格式
        Args:
            chat_message: 消息, 可能得到的消息格式如下:
            1. 文本消息: 你好
            2. 带有文件的消息: [
                {
                    "type": "text",
                    "content": "你好",
                },
                {
                    "type": "file",
                    "content": "file_id",
                }
            ]
        Returns: LLM格式的消息
        """
        content = chat_message.content
        if isinstance(chat_message, str):
            return {
                'role': chat_message.role,
                'content': content,
            }
        elif isinstance(chat_message, list):
            llm_message = []
            for content_message in chat_message.content:
                # 文本类型
                if content_message.get('type') == 'text':
                    llm_message.append({
                        'role': chat_message.role,
                        'content': content_message.content,
                    })
                # 文件类型
                elif content_message.get('type') == 'file':
                    file_id = content_message.content
                    # 根据文件id查询文件记录信息
                    file = ChatFilesService.find_file_by_id(file_id)
                    file_content = cls.load_file_content(file)

                    if file.suffix == 'png' or file.suffix == 'jpg':
                        llm_message.append({
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/{file.suffix};base64,{file_content}",
                            }})
                    elif file.suffix == 'pdf' or file.suffix == 'txt' or file.suffix == 'docx':
                        llm_message.append({
                            'type': 'text',
                            'text': file_content,
                        })
                    else:
                        raise ValueError(f"不支持的文件类型: {file.suffix}")

    @classmethod
    def load_file_content(cls, file: ChatFileMessage):
        """
        加载文件内容
        Args:
            file:

        Returns:

        """
        return ChatFilesService.read_file_content(file)
